package br.com.foxline.atlasmobile.novocadastro;

import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.adapter.NavDrawerListAdapter;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.util.NavDrawerItem;
import br.com.foxline.atlasmobile.util.SharedPreference;

@SuppressLint("NewApi")
public class CriarImovelActivity extends Activity {

	private static String IMOVEL = "getimovel";
	
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;

	private CharSequence mTitle;

	private String[] navMenuTitles;
	private TypedArray navMenuIcons;

	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;

	
	//imovel
	// DAO
	private ImovelDao imovelDao;
	private Imovel imovel;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_criar_imovel);

		mTitle = mDrawerTitle = getTitle();

		// BUSCA OS TEXTOS DO MENU DE strings.xml
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

		// BUSCA TODOS OS ICONES DO MENU
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// ADICIONAR ITEMS NO MENU LATERAL

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
				.getResourceId(0, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
				.getResourceId(1, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
				.getResourceId(2, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
				.getResourceId(3, -1), true, "22"));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
				.getResourceId(4, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
				.getResourceId(5, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
				.getResourceId(6, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
				.getResourceId(7, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons
				.getResourceId(8, -1)));

		// Recycle the typed array
		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		
		mDrawerList.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, // nav menu toggle icon
				R.string.app_name, // nav drawer open - description for
									// accessibility
				R.string.app_name // nav drawer close - description for
									// accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// EXIBE A PRIMEIRA TAB
			displayView(0);
		}
			
		//INICIANDO IMÓVEL
		initImovel();
	}

	private void initImovel(){
		imovelDao = new ImovelDao(getApplicationContext());
		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);
			avisoCadastroSincronizado();
		}else{
			imovel = new Imovel();
			imovel = imovelDao.find(15l);
		}
	}
	
	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		
		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	public void displayView(int position) {
		// update the main content by replacing fragments
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new DadosGeraisActivity();
			
			break;
		case 1:
			fragment = new CidadaoActivity();
			break;
		case 2:
			fragment = new DadosGeraisActivity();
			break;
		case 3:
			fragment = new DadosGeraisActivity();
			break;
		case 4:
			fragment = new DadosGeraisActivity();
			break;
		case 5:
			fragment = new DadosGeraisActivity();
			break;
		case 6:
			fragment = new DadosGeraisActivity();
			break;
		case 7:
			fragment = new DadosGeraisActivity();
			break;
		case 8:
			fragment = new DadosGeraisActivity();
			break;
		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
			
		} else {
			Log.e("MainActivity", "Erro ao criar o fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	public Imovel getImovel() {
		return imovel;
	}

	public void setImovel(Imovel imovel) {
		this.imovel = imovel;
	}


	/**
	 * Aviso de Imóvel já cadastrado
	 */
	private void avisoCadastroSincronizado() {
		
		if (imovel != null && !imovel.getEnviado()) {
			return;
		}
		
		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

		builder.setPositiveButton("Entendido",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});

		builder.setMessage(
				"ATENÇÃO ! O presente imóvel já foi sincronizado com a base, qualquer mudança nesse dispositivo será desconsiderada pelo sistema."
						+ " Para editar as informações contacte o administrado. ")
				.setTitle("Cadastro Sincronizado");

		dialog = builder.create();
		dialog.show();

	}
	
	public void salvarImovel(){
		if (imovel.getId() == null) {
			imovel.setCreateAt(new Date());
			imovel.setGroupCreate(getApplicationContext().getSharedPreferences(
					SharedPreference.PREFS_NAME, 0).getString(
					SharedPreference.GROUPS, ""));
			imovelDao.create(imovel);
		} else {
			imovel.setGroupUpdate(getApplicationContext().getSharedPreferences(
					SharedPreference.PREFS_NAME, 0).getString(
					SharedPreference.GROUPS, ""));
			imovelDao.update(imovel);
		}
		
	}
	

}
